﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NewsPublish.Service;
using Microsoft.AspNetCore.Hosting;
using NewsPublish.Model.Request;
using NewsPublish.Model.Response;
using System.Linq.Expressions;
using NewsPublish.Model.Entity;
using System.IO;

namespace NewsPublish.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class NewsController : Controller
    {
        private NewsService _newsService;
        private IHostingEnvironment _host;

        /// <summary>
        /// 构造函数 初始化变量
        /// </summary>
        public NewsController(NewsService newsService, IHostingEnvironment host)
        {
            this._newsService = newsService;
            this._host = host;
        }

        #region 新闻
        /// <summary>
        /// 新闻页面
        /// </summary>
        /// <returns>新闻首页</returns>
        public ActionResult Index()
        {
            var newsClassify = _newsService.GetNewsClassifyList();
            return View(newsClassify);
        }

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="calssifyID">新闻类别ID</param>
        /// <param name="keyword">新闻搜索关键字</param>
        /// <returns>新闻列表集合</returns>
        [HttpGet]
        public JsonResult GetNewsList(int pageIndex, int pageSize, int calssifyID, string keyword)
        {
            List<Expression<Func<News, bool>>> wheres = new List<Expression<Func<News, bool>>>();
            if (calssifyID > 0)
            {
                wheres.Add(c => c.NewsClassifyId == calssifyID);
            }

            if (!string.IsNullOrEmpty(keyword))
            {
                wheres.Add(c => c.Title.Contains(keyword.Trim()));
            }

            int total = 0;
            var news = _newsService.NewsPageQuery(pageSize, pageIndex, out total, wheres);
            return Json(new { total = total, data = news.data });
        }

        /// <summary>
        /// 新增新闻页面
        /// </summary>
        /// <returns></returns>
        public ActionResult NewsAdd() {
            var newsClassify = _newsService.GetNewsClassifyList();
            return View(newsClassify);
        }

        /// <summary>
        /// 添加新闻
        /// </summary>
        /// <param name="banner">banner新增对象</param>
        /// <param name="collection">图片参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddNews(AddNews news, IFormCollection collection)
        {
            if (news.NewsClassifyId<=0||string.IsNullOrEmpty(news.Title)||string.IsNullOrEmpty(news.Contents))
            {
                return Json(new ResponseModel { code = 0, result = "参数有误" });
            }

            var files = collection.Files;
            if (files.Count > 0)
            {
                var webRootPath = _host.WebRootPath;//获取wwwroot的路径
                string relativeDirPath = "\\NewsPic"; //相对路径
                string absolutePath = webRootPath + relativeDirPath; //图片文件保存绝对路径

                string[] fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" }; //允许上传的图片类型
                string extension = Path.GetExtension(files[0].FileName); //图片文件后缀名

                if (fileTypes.Contains(extension.ToLower()))
                {
                    //文件路径不存在则创建
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);
                    }

                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;//自定义文件名称
                    var filePath = absolutePath + "\\" + fileName;//文件保存完整路径

                    //将图片文件保存到指定目录中
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(stream);
                    }

                    news.Image = "/NewsPic/" + fileName;
                    return Json(_newsService.AddNews(news));//将页面输入的信息保存到数据库
                }
                else
                {
                    return Json(new ResponseModel { code = 0, result = "图片格式有误" });
                }
            }
            else
            {
                return Json(new ResponseModel { code = 0, result = "请上传图片文件" });
            }
        }

        /// <summary>
        /// 删除一条新闻
        /// </summary>
        /// <param name="newsID">新闻ID</param>
        /// <returns></returns>
        public JsonResult DelNews(int newsID)
        {
            if (newsID <= 0)
            {
                return Json(new ResponseModel { code = 0, result = "新闻不存在" });
            }

            return Json(_newsService.DelOneNews(newsID));
        }

        #endregion

        #region 新闻类别

        /// <summary>
        /// 新闻类别首页
        /// </summary>
        /// <returns></returns>
        public ActionResult NewsClassify()
        {
            var newsClassify = _newsService.GetNewsClassifyList();
            return View(newsClassify);
        }

        /// <summary>
        /// 新闻类别新增页面
        /// </summary>
        /// <returns></returns>
        public ActionResult NewsClassifyAdd()
        {
            return View();
        }

        /// <summary>
        /// 新增一条新闻类别
        /// </summary>
        /// <param name="newsClassify"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult NewsClassifyAddHandle(AddNewsClassify newsClassify)
        {
            if (string.IsNullOrEmpty(newsClassify.Name))
            {
                return Json(new ResponseModel { code = 0, result = "请输入新闻类别名称" });
            }
            return Json(_newsService.AddNewsClassify(newsClassify));
        }

        /// <summary>
        /// 新闻类别 编辑页面
        /// </summary>
        /// <param name="classifyID">新闻类别ID</param>
        /// <returns></returns>
        public ActionResult NewsClassifyEdit(int classifyID)
        {
            return View(_newsService.GetOneNewsClassify(classifyID));//查询当前编辑的新闻详情
        }

        /// <summary>
        /// 编辑一条新闻类别
        /// </summary>
        /// <param name="newsClassify"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult NewsClassifyEditHandle(EditNewsClassify newsClassify)
        {
            if (string.IsNullOrEmpty(newsClassify.Name))
            {
                return Json(new ResponseModel { code = 0, result = "请输入新闻类别名称" });
            }

            return Json(_newsService.EditNewsClassify(newsClassify));
        }
        #endregion


    }
}
